<template>
  <el-dialog
      title="ApiKey管理"
      width="500px"
      :visible="visible"
      :close-on-click-modal="false"
      destroy-on-close
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="settings-form"
    >
      <el-form-item label="ApiKey" prop="apiKey">
        <el-input
            v-model="form.apiKey"
            placeholder="请输入您的ApiKey"
            type="password"
            show-password
            clearable
        />
      </el-form-item>

      <el-form-item label="AI模型" prop="modelId">
        <el-radio-group v-model="modelInputType" @change="handleModelTypeChange">
          <el-radio label="select">从列表选择</el-radio>
          <el-radio label="custom">自定义输入</el-radio>
        </el-radio-group>

        <el-select
            v-if="modelInputType === 'select'"
            v-model="form.modelId"
            placeholder="请选择要使用的AI模型"
            clearable
            style="margin-top: 10px; width: 100%"
        >
          <el-option
              v-for="model in models"
              :key="model.modelId"
              :label="`${model.modelName} (${model.modelId})`"
              :value="model.modelId"
          />
        </el-select>

        <el-input
            v-else
            v-model="form.modelId"
            placeholder="请输入自定义模型ID"
            clearable
            style="margin-top: 10px"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave">保存设置</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { apiKeyStore } from '@/stroe/sql/ApiKey.js';

// 模型列表数据
const models = [
  { "modelName": "通义千问基础版", "modelId": "qwen-plus" },
  { "modelName": "通义千问增强版", "modelId": "qwen-max" },
  { "modelName": "通义千问多模态版", "modelId": "qwen-vl-plus" },
  { "modelName": "通义千问7B参数版", "modelId": "qwen-7b-chat" },
  { "modelName": "Llama2 70B对话模型", "modelId": "llama2-70b-chat" },
  { "modelName": "百川2 13B对话模型", "modelId": "baichuan2-13b-chat" },
  { "modelName": "ChatGLM3 6B模型", "modelId": "chatglm3-6b" },
  { "modelName": "WizardLM 13B模型", "modelId": "wizardlm-13b-v1.2" },
  { "modelName": "CodeGeeX2 6B代码模型", "modelId": "codegeex2-6b" },
  { "modelName": "DeepSeek R1模型", "modelId": "deepseek-r1" }
];

// 表单相关
const formRef = ref();
const form = ref({
  apiKey: '',
  modelId: ''
});

// 模型输入类型：select-从列表选择，custom-自定义输入
const modelInputType = ref('select');

// 表单验证规则
const rules = {
  apiKey: [
    { required: true, message: '请输入ApiKey', trigger: 'blur' }
  ],
  modelId: [
    { required: true, message: '请选择或输入模型ID', trigger: ['blur', 'change'] }
  ]
};

// 对话框显示状态
const visible = ref(false);

// 处理模型输入类型变更
const handleModelTypeChange = (type: string) => {
  // 如果从自定义切换到选择模式，尝试匹配已有模型
  if (type === 'select' && form.value.modelId) {
    const matched = models.find(m => m.modelId === form.value.modelId);
    if (!matched) {
      form.value.modelId = '';
    }
  }
};

// 从store加载数据
const loadData = () => {
  form.value.apiKey = apiKeyStore.apiKey || '';
  form.value.modelId = apiKeyStore.model || '';

  // 判断现有模型ID是否在预设列表中，自动选择输入模式
  const isInPreset = models.some(m => m.modelId === form.value.modelId);
  modelInputType.value = isInPreset ? 'select' : 'custom';
};

// 保存设置
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();

    // 保存到store
    apiKeyStore.setApiKey(form.value.apiKey);
    apiKeyStore.setModel(form.value.modelId);

    ElMessage.success('设置保存成功');
    visible.value = false;
  } catch (error) {
    return;
  }
};

// 关闭对话框
const handleClose = () => {
  visible.value = false;
};

// 提供外部控制对话框显示的方法
const openDialog = () => {
  loadData();
  visible.value = true;
};

// 暴露方法给父组件
defineExpose({
  openDialog
});

// 初始化时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.settings-form {
  margin-top: 15px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-radio-group {
  display: flex;
  gap: 15px;
}
</style>
